package http

import (
	"github.com/gin-gonic/gin"
	"github.com/astaxie/beego"
	"github.com/DeanThompson/ginpprof"
	"net/http"
	"github.com/itsjamie/gin-cors"
	"time"
	"strings"
	"context"
	"log"
	"fmt"
	"publish/app/account/controller"
)

var (
	webserver *http.Server
)


func StartServer() {
	router := gin.Default()
	router.Use(Cors())
	router.Use(StaticFile())

	runmode := beego.AppConfig.DefaultString("runmode", "debug")
	if runmode == "debug" {
		ginpprof.Wrapper(router)
	}

	Router(router)

	addr := beego.AppConfig.String("http_ip") + ":" + beego.AppConfig.String("http_port")

	webserver = &http.Server{
		Addr:    addr,
		Handler: router,
	}

	if err := webserver.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatalln("listen: %s\n", err)
	}
}

func StopServer() {
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()
	if err := webserver.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown:", err)
	}
}

func Cors() gin.HandlerFunc {
	return cors.Middleware(cors.Config{
		Origins:         "*",
		Methods:         "GET, PUT, POST, DELETE",
		RequestHeaders:  "Origin, Authorization, Content-Type",
		ExposedHeaders:  "",
		MaxAge:          50 * time.Second,
		Credentials:     true,
		ValidateHeaders: false,
	})
}

func StaticFile() gin.HandlerFunc {
	fmt.Println("StaticFile")
	return func(c *gin.Context) {
		if strings.Index(c.Request.URL.Path, "api/") >= 0 || strings.Index(c.Request.URL.Path, "debug/") >= 0 {
			c.Next()
			return
		}
		http.ServeFile(c.Writer, c.Request, "./static"+c.Request.URL.Path)
	}
}

func Json(handler func(*gin.Context) controller.Result) gin.HandlerFunc{
	return func(ctx *gin.Context){
		result := handler(ctx)
		ctx.JSON(200, result)
	}
}
